package com.sunmouse.toolkit.fragment.ftp;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.sunmouse.toollib.adapter.OnChildClickListener;
import com.sunmouse.toollib.receiver.OnReceiveListener;
import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toollib.utils.StringUtils;
import com.sunmouse.toollib.utils.ThreadPoolUtils;
import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toollib.utils.system.NetUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.adapter.FileAdapter;
import com.sunmouse.toolkit.receiver.BackReceiver;
import com.sunmouse.toolkit.constant.Config;
import com.sunmouse.toolkit.constant.Value;
import com.sunmouse.toolkit.fragment.BaseFragment;
import com.sunmouse.toolkit.ftp.FTPHelper;
import com.sunmouse.toolkit.ftp.FileBean;
import com.sunmouse.toolkit.ftp.SimpleOnFTPListener;
import com.sunmouse.toolkit.util.NavUtils;

import org.apache.commons.net.ftp.FTPFile;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class FileListFragment extends BaseFragment {
    @BindView(R.id.file_lv)
    ListView fileLv;
    Unbinder unbinder;

    private FTPHelper mFtp;
    private String ip;
    private int port;
    private String name;
    private String psw;

    private ArrayList<FileBean> files;
    private FileAdapter mAdapter;
    private HashMap<String, String> track;

    private NavUtils mNav;
    private OnChildClickListener mOnChildClickListener;

    private BackReceiver mBackReceiver;

    public FileListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_file_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    public void setOnChildClickListener(OnChildClickListener mOnChildClickListener) {
        this.mOnChildClickListener = mOnChildClickListener;
    }

    @Override
    public void init() {
        mFtp = FTPHelper.getInstance(getActivity());
        mFtp.setListener(mFTPListener);
        ip = mPersistentUtils.readString(Config.Key.IP);
        port = mPersistentUtils.readInt(Config.Key.PORT);
        name = mPersistentUtils.readString(Config.Key.USERNAME);
        psw = mPersistentUtils.readString(Config.Key.PSW);

        mBackReceiver = new BackReceiver();
        getActivity().registerReceiver(mBackReceiver, new IntentFilter(Value.Action.BACK));
        mBackReceiver.setOnReceiveListener(mOnReceiveListener);

        track = new HashMap<>();

        files = new ArrayList<>();
        mAdapter = new FileAdapter(files, getActivity());
        this.fileLv.setAdapter(mAdapter);
        this.fileLv.setOnItemClickListener(mOnItemClickListener);

        //init action bar
        mNav = NavUtils.newInstance(getActivity());
        mNav.setBackIcon(R.mipmap.nav_menu);
        mNav.setTitle("Home");
        mNav.setOnBackClickListener(this);

        if (StringUtils.isEmpty(ip) || StringUtils.isEmpty(name) || StringUtils.isEmpty(psw) || port == -2) {
            getActivity().sendBroadcast(switchIntent(0));
        } else {
            loadingData(1);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        LogUtils.d("-----------onResume");
    }

    /**
     * @param i
     * @return
     */
    private Intent switchIntent(int i) {
        mIntent = new Intent(Value.Action.SWITCH);
        mIntent.putExtra(Config.Key.INDEX, i);
        return mIntent;
    }

    @Override
    public void loadingData(int page) {
        if (!NetUtils.isNetConnected(getActivity())) {
            ToastUtils.simpleToast(getActivity(), "抱歉网络未连接，请连接后尝试！");
            return;
        }
        if (files.size() > 0) files.clear();
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                mFtp.connect(ip, port, name, psw);
                files.addAll(mFtp.getFiles());
                mHandler.sendEmptyMessage(1);
            }
        });
    }

    private AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            FileBean b = files.get(position);
            if (b.getFileType() == FTPFile.DIRECTORY_TYPE) {
                loadingSubContent(b.getName());
                track.put(b.getName(), b.getParent());
            } else {
                //handle files
            }
        }
    };

    private void loadingSubContent(final String parent) {
        if (!NetUtils.isNetConnected(getActivity())) {
            ToastUtils.simpleToast(getActivity(), "抱歉网络未连接，请连接后尝试！");
            return;
        }
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                files.clear();
                files.addAll(mFtp.getFiles(parent));
                mHandler.sendEmptyMessage(1);

            }
        });

    }

    /**
     * ftp response listener
     */
    private SimpleOnFTPListener mFTPListener = new SimpleOnFTPListener() {
        @Override
        public void onReady() {
            super.onReady();
        }

        @Override
        public void onLogin() {
            super.onLogin();
        }

        @Override
        public void onFailure() {
            super.onFailure();
        }
    };

    /**
     * receiver listener (decide whether to go back or go to parent)
     */
    private OnReceiveListener mOnReceiveListener = new OnReceiveListener() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int type = intent.getIntExtra(Config.Key.TYPE, -2);
            if (type == Value.BACK) {
                if (files.size() < 1) return;//just for safe
                String par = files.get(0).getParent();
                String gp = track.get(par);
                if (StringUtils.isEmpty(gp)) {
                    getActivity().finish();
                } else if (gp.equals("root")) {
                    loadingData(1);
                } else {
                    loadingSubContent(gp);
                }
            }else if (type==Value.UPDATE){
                loadingData(1);
            }
        }
    };


    @Override
    public void onClick(View v) {
        if (mOnChildClickListener != null) {
            mOnChildClickListener.onClick(v, 0);
        }
    }

    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        if (msg.what == 1) {
            mAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        getActivity().unregisterReceiver(mBackReceiver);
//        mBus.unregister(this);
    }
}
